import { Component, OnInit } from '@angular/core';
import { IonicModule, Platform } from '@ionic/angular';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import {Router, ActivatedRoute} from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ToastController } from '@ionic/angular';
import { Storage } from '@ionic/storage';
import { CommonService } from 'src/app/core/common/common.service';
import { Utils } from 'src/app/core/common/Untils';
import { Plugins } from '@capacitor/core';
const { App } = Plugins;

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {

  constructor(
    private router:Router,
    private http: HttpClient,
    private platform: Platform,
    private toastController: ToastController,
    private commonService: CommonService) { }

  companyList: any[];
  userName = 'admin';
  password = 'zyr123!@#';

  ngOnInit() {

  }

  // 公司下拉选择
  getCompanyDown() {
    this.http.get('/api/Common/GetAllCompanyDown').subscribe((res: any) => {
        // res = res.json();
        console.log(res);
        this.companyList = res;
      });
  }


  // 登录
  login(){
    if (this.userName!=='' && this.password!==''){
    const body=`grant_type=password&username=${ this.userName + '_9f56' + '_edfefca6-bbe1-4a1a-afcc-f750add1d053'}&password=${this.password}&clientid=1`;
    const header=new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
    this.http.post('Token',body,{headers:header}).toPromise().then(async (data: any) =>{
        const token = data.access_token;
        // 存储token并跳转
        await this.commonService.setToken(token);
      }).catch((data: any) => {
        console.log(data.error.error);
        this.presentToast(data.error.error);
      });
    }
    else{
      this.presentToast('登录信息不能为空');
    }
  }

  // Toast消息提示
  async presentToast(msg: any) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 4000
    });
    toast.present();
  }


}